﻿﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SPCFMedicineInformer.DocumentTypes;
using Vega.USiteBuilder;
using umbraco.MacroEngines;
using umbraco.cms.businesslogic.web;
using umbraco.BusinessLogic;
using SPCFMedicineInformer.Constants;
using umbraco.NodeFactory;
using SPCFMedicineInformer.Helpers;
using System.Text;
using System.Web.Configuration;
using umbraco;

namespace SPCFMedicineInformer.Masterpages
{
    public partial class Admin_ConditionDetail : System.Web.UI.MasterPage
    {
        int id;
        public IEnumerable<MedicineItem> MedList { get; set; }
        public IEnumerable<Symptom> SympList { get; set; }
        string medicineIdTag = string.Empty;
        public List<string> HiddenMedicineList { get; set; }
        public List<string> HiddenSymptomList { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            int tempInt;
            id = Request.QueryString["id"] != null ? int.TryParse(Request.QueryString["id"].ToString(), out tempInt) ? tempInt : 1 : 0;
            bool isNew = Request.QueryString["n"] != null ? Request.QueryString["n"].ToString() == "1" ? true : false : false;
            btnDelete.Visible = id > 0 ? true : false;
            if (!IsPostBack)
            {
                BindDropdowns();
                if (id > 0)
                {
                    Node node = new Node(id);
                    var n = node != null && node.NodeTypeAlias == "Condition" ? ContentHelper.GetByNodeId<Condition>(id) : null;
                    if (n != null)
                    {
                        txtName.Text = n.ConditionName;
                        txtDescription.Text = n.Description;
                        hiddenMedList.Value = n.MedicineTag;
                        hiddenSympList.Value = n.SymptomTag;
                        slideImage.ImageUrl = n.ImageUrl;
                        ShowExistingImage(!string.IsNullOrEmpty(n.ImageUrl) ? true : false);
                        cbIsCommonCondition.Checked = n.IsCommonCondition;

                        if (isNew)
                            FormHelper.ShowMessage(MessageType.Done, "Condition Succesfully Saved!", MsgLiteral);
                        ShowContent(true);
                    }
                    else
                    {
                        ShowContent(false);
                    }
                }
                else
                {
                    ShowExistingImage(false);
                }
            }
            HiddenMedicineList = hiddenMedList.Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
            HiddenSymptomList = hiddenSympList.Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
            BindList();
            
        }
        void ShowContent(bool b)
        {
            plcContent.Visible = b;
            plcError.Visible = !b;
        }
        void Update()
        {
            if (id > 0)
            {
                var d = new Document(id);
                if (d != null)
                {
                    TransferDetailsToUmbraco(d);       
                }
            }

        }
        int Add()
        {
            DocumentType docType = DocumentType.GetByAlias("Condition");
            
            var conditionFolder = NodeLocator.GetNodeOfExactType<ConditionFolder>();
            if (conditionFolder != null)
            {
                Document newDoc = Document.MakeNew(txtName.Text, docType, User.GetUser(0), conditionFolder.Id);
                TransferDetailsToUmbraco(newDoc);
                if (newDoc != null)
                    return newDoc.Id;
            }
            
            return 0;
        }
        void BindDropdowns()
        {
            var categoryList = NodeLocator.GetNodesOfExactType<MedicineCategory>();
            ddlCategory.Items.Clear();
            ddlCategory.DataSource = categoryList;
            ddlCategory.DataTextField = "Name";
            ddlCategory.DataValueField = "Id";
            ddlCategory.DataBind();
            ddlCategory.Items.Insert(0, new ListItem("Choose...", "0"));

            ddlCategoriesForSymptoms.Items.Clear();
            ddlCategoriesForSymptoms.DataSource = categoryList;
            ddlCategoriesForSymptoms.DataTextField = "Name";
            ddlCategoriesForSymptoms.DataValueField = "Id";
            ddlCategoriesForSymptoms.DataBind();
            ddlCategoriesForSymptoms.Items.Insert(0, new ListItem("Choose...", "0"));
            
        }
        void TransferDetailsToUmbraco(Document d)
        {
            if (plcNewImage.Visible)
            {
                d.getProperty(UmbracoPropertyName.IMAGE_URL).Value = UploadImage(d.Id);
            }
            d.Text = txtName.Text;
            d.getProperty(UmbracoPropertyName.CONDITION_NAME).Value = txtName.Text;
            d.getProperty(UmbracoPropertyName.CONDITION_DESCRIPTION).Value = txtDescription.Text;
            d.getProperty(UmbracoPropertyName.CONDITION_MEDICINES_TAG).Value = hiddenMedList.Value;
            d.getProperty(UmbracoPropertyName.CONDITION_SYMPTOMS_TAG).Value = hiddenSympList.Value;
            d.getProperty(UmbracoPropertyName.IS_COMMON_CONDITION).Value = cbIsCommonCondition.Checked;
            d.Publish(User.GetUser(0));
            umbraco.library.UpdateDocumentCache(d.Id);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                if (id > 0)
                {
                    Update();
                    FormHelper.ShowMessage(MessageType.Done, "Symptom Succesfully Saved!", MsgLiteral);
                }
                else
                {
                    id = Add();
                    Response.Redirect("/admin/utilities/conditions-listing/condition-entry.aspx?id=" + id.ToString() + "&n=1");
                }
            }

        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/conditions-listing/");
        }
        bool IsValidate()
        {
            bool result = true;
            var sb = new StringBuilder();
            var msgFormat = "<p class=\"{0}\">{1}</p>";
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Condition Name is required!"));
                result = false;
            }
            else if (id == 0)
            {
                if (NodeLocator.GetNodesOfExactType<Condition>().Where(node => node.ConditionName.ToLower() == txtName.Text.ToLower()).ToList().Count > 0)
                {
                    result = false;
                    sb.AppendLine(string.Format(msgFormat, "msg error", "Condition Name exist!"));
                }
            }
            if (!result)
            {
                MsgLiteral.Visible = true;
                MsgLiteral.Text = sb.ToString();
            }
            return result;
        }
        void BindList()
        {
            MedList = NodeLocator.GetNodesOfExactType<MedicineItem>().Where(node => node.Parent().ParentId.ToString() == ddlCategory.SelectedValue).OrderBy(node=>node.Name);
            SympList = NodeLocator.GetNodesOfExactType<Symptom>().Where(node => node.Parent().ParentId.ToString() == ddlCategoriesForSymptoms.SelectedValue).OrderBy(node=>node.Name);
        }
        #region ImageUploading
        protected void lbUploadNew_Click(object sender, EventArgs e)
        {
            ShowExistingImage(false, true);
        }
        protected void lbCanceUpload_Click(object sender, EventArgs e)
        {
            ShowExistingImage(true);
        }
        void ShowExistingImage(bool value, bool cancel = false)
        {
            plcExistingImage.Visible = value;
            lbCancelUpload.Visible = cancel;
            plcNewImage.Visible = !value;
        }
        string UploadImage(int id)
        {
            if (FileUpload1.HasFile)
            {
                string strFile = WebConfigurationManager.AppSettings["ImagePath"] + id.ToString() + "-" + FileUpload1.FileName;
                string filepath = Server.MapPath(strFile);
                FileUpload1.SaveAs(filepath);
                ShowExistingImage(true);
                slideImage.ImageUrl = strFile;
                return strFile.Remove(0, 1);
            }
            return "";
        }
        #endregion
        void Delete(int id)
        {
            if (id > 0)
            {
                Document doc = new Document(id);
                if (doc.Published)
                {
                    doc.UnPublish();
                    library.UnPublishSingleNode(doc.Id);
                }
                doc.delete();
                Response.Redirect("/admin/utilities/conditions-listing/");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete(id);
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/conditions-listing/condition-entry");
        }
    }
}